<template>
  <div v-loading="loading">
    <table class="table table-bordered mt-3 mb-1">
      <tbody>
        <tr>
          <td colspan="10" class="font-weight-bold" data-font-bold="true">
            户口数据
            <el-button type="text" v-if="!isViewMode" class="py-0" @click="handlerEdit">
              <i class="fa fa-edit"></i>
            </el-button>
          </td>
        </tr>
        <tr>
          <td width="10%">姓名</td>
          <td width="10%">性别</td>
          <td width="18%">身份证号</td>
          <td width="12%">年龄</td>
          <td width="12%">关系</td>
          <td colspan="2" width="13%">职业</td>
          <td width="12">联系电话</td>
          <td colspan="2" width="13%">备注</td>
        </tr>
        <tr v-if="!customerFamily.length">
          <td>-</td>
          <td>-</td>
          <td>-</td>
          <td>-</td>
          <td>-</td>
          <td colspan="2">-</td>
          <td>-</td>
          <td colspan="2">-</td>
        </tr>
        <tr v-for="(family, index) in customerFamily" :key="index">
          <td>{{ family.real_name || '-' }}</td>
          <td>{{ enumSexType[family.sex] || '-' }}</td>
          <td>{{ family.id_card || '-' }}</td>
          <td>{{ family.age || '-' }}</td>
          <td>{{ family.relation || '-' }}</td>
          <td colspan="2">{{ family.career || '-' }}</td>
          <td>{{ family.phone_number || '-' }}</td>
          <td colspan="2">{{ family.remark || '-' }}</td>
        </tr>
      </tbody>
    </table>

    <el-dialog
      :visible.sync="visible"
      :close-on-click-modal="false"
      append-to-body
      title="修改家庭成员信息"
      width="1000px"
    >
      <table class="table table-bordered mt-3 mb-1">
        <tbody>
          <tr>
            <td width="10%">姓名</td>
            <td width="10%">性别</td>
            <td width="16%">身份证号</td>
            <td width="12%">年龄</td>
            <td width="12%">关系</td>
            <td colspan="2" width="10%">职业</td>
            <td width="15%">联系电话</td>
            <td colspan="2" width="15%">备注</td>
          </tr>
          <tr v-for="(p, index) of editData" :key="index">
            <td class="report-input-td">
              <el-input v-model="p.real_name" class="text-center" placeholder="输入姓名"></el-input>
            </td>
            <td class="report-input-td">
              <c-select
                v-model="p.sex"
                class="w-100"
                placeholder="选择性别"
                clearable
                :options="enumSexType"
              ></c-select>
            </td>
            <td class="report-input-td">
              <el-input
                v-model="p.id_card"
                @change="v => setIdCardInfo(v, p)"
                class="text-center"
                placeholder="输入身份证"
              ></el-input>
            </td>
            <td class="report-input-td">
              <el-input
                v-model="p.age"
                class="text-center"
                placeholder="输入年龄"
                type="number"
              ></el-input>
            </td>
            <td class="report-input-td">
              <el-input v-model="p.relation" class="text-center" placeholder="输入关系"></el-input>
            </td>
            <td class="report-input-td" colspan="2">
              <el-input v-model="p.career" class="text-center" placeholder="输入职业"></el-input>
            </td>
            <td class="report-input-td">
              <el-input
                v-model="p.phone_number"
                class="text-center"
                placeholder="输入联系电话"
              ></el-input>
            </td>

            <td class="report-input-td" colspan="2">
              <div class="d-flex align-items-center">
                <div class="flex-1 px-1">
                  <el-input
                    v-model="p.remark"
                    class="text-center flex"
                    placeholder="备注"
                  ></el-input>
                </div>
                <el-button
                  class="td-inner-btn px-3 text-danger"
                  type="text"
                  @click="deleteData(p.datum_customer_family_emp_id, index)"
                >
                  <i class="fa fa-trash"></i>
                </el-button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <el-button-group class="mb-2 mt-1">
        <el-button size="small" @click="editRowAdd">
          <i class="fa fa-indent"></i>
          添加一行
        </el-button>
      </el-button-group>
      <div class="text-center">
        <el-button type="primary" @click="saveData" :loading="saveLoading" style="min-width: 100px">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { enumSexType } from '@/credit/plugins/enum'
import { getResultArray } from '@/gov/components/creditFile/index'
import { idCardValidate, idCardFormat } from '@vimi/utils-tool'
import { checkPhoneNumber } from '@/common/plugins/validator'
export default {
  components: {},
  props: {
    queryId: {
      type: String,
      default: '',
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumSexType,
      loading: false,
      visible: false,
      saveLoading: false,
      tableName: 'datum_customer_family_emp',
      customerFamily: [],
      editData: [],
    }
  },
  computed: {
    isViewMode() {
      return this.viewMode
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.getData()
      },
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    // 按身份证计算年龄和性别
    setIdCardInfo(val, p) {
      val = val.trim()
      if (idCardValidate(val)) {
        const info = idCardFormat(val)
        this.$set(p, 'sex', String(info.gender ? 2 : 1))
        const date = new Date()
        // date.getFullYear()
        let age = date.getFullYear() - info.year

        const birYear = date.getFullYear()
        const birMonth = String(date.getMonth() + 1).padStart(2, '0')
        const birDay = String(date.getDate()).padStart(2, '0')
        const birMD = `-${birMonth}-${birDay}`
        if (`${birYear}${birMD}` < `${birYear}-${info.month}-${info.day}`) {
          age++
        }
        this.$set(p, 'age', age)
      }
    },
    getData() {
      this.loading = true
      const params = { 'customer_related_id.eq': this.queryId }
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          this.customerFamily = getResultArray(res)
          this.$emit('back', this.customerFamily)
          this.editData = this.customerFamily.map(item => {
            return { ...item }
          })
          if (this.editData.length < 5) {
            this.addTemp(5 - this.editData.length)
          }
        })
        .catch(res => {
          this.$message.error(`请求家庭成员信息失败${res}`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handlerEdit() {
      this.editData = []
      this.visible = true
      this.editData = this.customerFamily.map(item => {
        return { ...item }
      })
      if (this.editData.length < 5) {
        this.addTemp(5 - this.editData.length)
      }
    },
    addTemp(len) {
      for (let i = 0; i < len; i++) {
        this.editData.push({})
      }
    },
    editRowAdd() {
      this.addTemp(1)
    },
    deleteItem(index) {
      this.editData.splice(index, 1)
    },
    saveData() {
      let data = []
      for (let item of this.editData) {
        if (item.datum_customer_family_emp_id && !item.real_name) {
          return this.$message.warning('请输入姓名')
        }
        if (item.phone_number && !checkPhoneNumber(item.phone_number)) {
          return this.$message.warning(`${item.real_name || ''} 电话号码有误`)
        }
        if (item.id_card && !idCardValidate(item.id_card)) {
          return this.$message.warning(`${item.real_name || ''} 身份证号码有误`)
        }
        if (item.real_name) {
          item.customer_related_id = this.queryId
          data.push(item)
        }
      }
      if (!data.length) {
        return
      }
      this.saveLoading = true
      this.$api
        .updateBatch(this.$serviceName, this.tableName, data)
        .then(() => {
          this.$message.success('保存成功')
          this.getData()
          this.visible = false
        })
        .catch(() => {
          this.$message.error('保存失败')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    deleteData(id, index) {
      if (!id) {
        this.deleteItem(index)
        return
      }
      this.$utils
        .msgbox({
          message: '确定删除?',
          beforeClose: () => this.$api.deleteData(this.$serviceName, this.tableName, id),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/gov/components/creditFile/style.scss';
</style>
